import {AnyParams} from "@/common/httptypes";
import {util} from "@/common/util";
import {HSearchTreePops} from "@/components/ant-ext/HSearchTree";
import React, {Key} from "react";
import {Tag} from "antd";

const colors = ['#e9c479', '#2db7f5', '#108ee9', '#87d068'];
const colorMapping: AnyParams<any> = {};
const getColor = (key: string) => {
    let index = colorMapping[key];
    if (util.NotNull(index)) {
        return colors[index];
    } else {
        index = Object.keys(colorMapping).length;
        colorMapping[key] = index;
        return colors[index];
    }
};

export function ScanSearchTreeExtText(searchValue: string, expandedKeys: Key [], parentKey: Key | undefined, data: HSearchTreePops["treeData"]): HSearchTreePops["treeData"] {
    if (data) {
        return data.map((item) => {
            const {tag, level} = item
            let textNode: React.ReactNode
            let tagNode: React.ReactNode
            if (searchValue !== "") {
                const titleStr = String(item.title)
                const index = titleStr.indexOf(searchValue);
                const beforeStr = titleStr.substring(0, index);
                const afterStr = titleStr.slice(index + searchValue.length);
                if (index > -1) {
                    if (parentKey) {
                        expandedKeys.push(parentKey)
                    }

                    textNode = <span>
                            {beforeStr}
                        <span style={{color: '#ff1811'}}>{searchValue}</span>
                        {afterStr}
                        </span>
                } else {
                    textNode = <>{item.title}</>
                }
            } else {
                textNode = <>{item.title}</>
            }
            if (tag) {
                tagNode = <Tag style={{marginLeft: '10px'}} color={getColor(String(level))}>
                    {tag}
                </Tag>
            }
            return {
                title: <>{textNode}{tagNode}</>,
                key: item.key,
                children: ScanSearchTreeExtText(searchValue, expandedKeys, item.key, item.children as HSearchTreePops["treeData"])
            };
        })
    } else {
        return []
    }
}
